extends NodeState

# 停球时的重力
const STOPPING_GRAVITY := GlobalConstants.BALL_GRAVITY * 2


var ball: Ball:
	get:
		return state_matchine.root as Ball


var carrier: Player = null
var dribble_time: float


func _on_process(delta : float) -> void:
	process_carry(delta)
	process_animation()
	# 持球时球会快速落下并轻微反弹
	ball.process_bounce(delta, ball.bounciness * 0.5, STOPPING_GRAVITY)



func _on_enter(_data: NodeStateData) -> void:
	carrier = ball.carrier
	dribble_time = 0.0
	# 清空高度
	# ball.reset_height()



func _on_exit() -> void:
	carrier = null
	ball.carrier = null



func process_carry(delta : float):
	if not carrier:
		return

	var vx := 0.0
	var direction := carrier.character_orientation()
	dribble_time += delta

	# 运球时，随时间在 x轴波动
	if carrier.velocity.x != 0.0:
		vx = cos(dribble_time * ball.dribble_frequency) * ball.dribble_intensity
		vx = clamp(vx, 0.0, INF) if direction > 0 else clamp(vx, -INF, 0.0)

	ball.position = carrier.position + Vector2(vx + direction * ball.offset_carrier.x, ball.offset_carrier.y)



func process_animation():
	if not carrier:
		ball.animation_player.play(Ball.ANIMATION_IDLE)
		return
	if carrier.velocity == Vector2.ZERO:
		ball.animation_player.play(Ball.ANIMATION_IDLE)
		return
	# 根据角色的方向播放滚动动画
	if carrier.character_orientation() >= 0:
		ball.animation_player.play(Ball.ANIMATION_ROLL)
	else:
		ball.animation_player.play(Ball.ANIMATION_ROLL_BACK)
